package com.pjb.springbootjjwt.store.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 主键索引存储
 */
public class TreeMapUtil {


    public static String toText(Map<String, String> map) {
        String text = "";
        for (Map.Entry<String, String> entrySet : map.entrySet()) {
            String line = entrySet.getValue() + ":" + entrySet.getKey() + RandomAccessFileUtil.sp;
            text += line;
        }
        return text;
    }

    public static Map toMap(String text) {
        String[] arr = text.split(RandomAccessFileUtil.sp);
        Map<String, String> map = new TreeMap<>();
        String[] l;
        for (String line : arr) {
            l = line.split(":");
            map.put(l[0], l[1]);
        }
        return map;
    }

    public static String removeKey(String table, String key) throws IOException {
        String c = FileUtil.read(table + ".idx");
        String[] arr = c.split(";\r\n");
        List<String> r = new ArrayList<>();
        for (String l : arr) {
            if (l.startsWith(key)) continue;
            r.add(l);
        }

        String text = "";
        for (String item : r) {
            text += item;
        }
        return text;
    }

    /**
     * 获取文件最大行数
     *
     * @param table
     * @return
     * @throws IOException
     */
    public static int getMaxNo(String table) throws IOException {
        String c = FileUtil.read(table + ".idx");
        String[] arr = c.split(";\r\n");
        int count = 0;
        for (String l : arr) {
            if (StringUtils.isEmpty(l)) continue;
            count++;
        }
        return count - 1;
    }

    public static void add() {

    }

    public static void delete() {

    }

    public static void update() {

    }

    public static void main(String[] args) throws Exception {
        Map<String, String> map = new TreeMap();
        map.put("" + 1, "" + 1);
        map.put("" + 2, "" + 11);
        map.put("" + 3, "" + 111);
        map.put("" + 4, "" + 1111);
        map.put("" + 5, "" + 1111);
        map.put("" + 6, "" + 1111);
        System.out.println(toText(map));
        map = toMap(toText(map));
        System.out.println(map);

        map.remove("3");
        System.out.println(toText(map));
        System.out.println(toMap(toText(map)));
        FileUtil.use("test");

        System.out.println(getMaxNo("abc.frm"));
    }

}
